using System;
using System.IO;
using UnityEditor;
using UnityEngine;
using static UnityEngine.RenderTexture;

/// <summary> 截图编辑器界面代码 </summary>
public class ScreenshotEditor : EditorWindow
{
    static ScreenshotEditor _screenshotEditor;

    [MenuItem("Tools/截图工具", false)]
    private static void ShowWindow()
    {
        if (_screenshotEditor == null) _screenshotEditor = GetWindow<ScreenshotEditor>(false, "截图工具");
        else _screenshotEditor.Close();

        // 设置初始化
        if (EditorPrefs.GetString("_savePath") != string.Empty) return;
        EditorPrefs.SetInt("_width", 1280);
        EditorPrefs.SetInt("_height", 720);
        EditorPrefs.SetBool("_isAlpha", false);
        var path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // 桌面地址
        EditorPrefs.SetString("_savePath", path);
    }

    void OnGUI()
    {
        var title01 = new GUIStyle("HelpBox")
        {
            alignment = TextAnchor.MiddleCenter,
            stretchWidth = true,
            wordWrap = false,
            fontSize = 12
        };

        GUILayout.Label("截图工具", title01);
        GUILayout.BeginHorizontal("box");
        {
            EditorGUIUtility.labelWidth = 60;
            var width = EditorGUILayout.IntField("宽:", EditorPrefs.GetInt("_width"));
            var height = EditorGUILayout.IntField("高:", EditorPrefs.GetInt("_height"));
            var isAlpha = EditorGUILayout.Toggle("通道", EditorPrefs.GetBool("_isAlpha"));
            EditorPrefs.SetInt("_width", width);
            EditorPrefs.SetInt("_height", height);
            EditorPrefs.SetBool("_isAlpha", isAlpha);
        }
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal("box");
        {
            EditorGUILayout.LabelField("保存路径:", EditorPrefs.GetString("_savePath"));
            if (GUILayout.Button("...", GUILayout.Width(80), GUILayout.Height(20)))
            {
                var path = EditorUtility.OpenFolderPanel("目录", "文件夹", null);
                if (!string.IsNullOrEmpty(path)) EditorPrefs.SetString("_savePath", path);
            }
        }
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal("box");
        {
            if (GUILayout.Button("截图", GUILayout.Height(20)))
                ScreenshotPNG.Create(EditorPrefs.GetInt("_width"), EditorPrefs.GetInt("_height"), EditorPrefs.GetString("_savePath"), "Screenshot", EditorPrefs.GetBool("_isAlpha"));
        }
        GUILayout.EndHorizontal();
    }
}

// <summary> PNG输出代码 </summary>
public static class ScreenshotPNG
{
    /// <summary> 创建 </summary>
    public static void Create(int width, int height, string savePath, string textureName, bool alpha)
    {
        var camera = Camera.main;
        if (camera == null)
        {
            Debug.LogError("需要设置一个MainCamera标签相机!");
            return;
        }

        // 创建文理镜头渲染
        var renderTexture = GetTemporary(width, height, 24, RenderTextureFormat.ARGB32);
        camera.targetTexture = renderTexture;
        camera.Render();

        // 生成图片
        var result = SaveRenderTexture(renderTexture, savePath, textureName, alpha);
        ReleaseTemporary(renderTexture);
        camera.targetTexture = null;

        if (result) Debug.Log("保存成功！");
        else Debug.LogError("保存出现意外的错误！");
    }

    /// <summary> 保存渲染文理 </summary>
    static bool SaveRenderTexture(RenderTexture renderTexture, string savePath, string textureName, bool alpha)
    {
        TextureFormat textureFormat;
        textureFormat = alpha ? TextureFormat.ARGB32 : TextureFormat.RGB24;
        var active = RenderTexture.active;
        RenderTexture.active = renderTexture;
        var png = new Texture2D(renderTexture.width, renderTexture.height, textureFormat, false);
        png.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
        var bytes = png.EncodeToPNG();
        if (!Directory.Exists(savePath)) Directory.CreateDirectory(savePath);
        var file = File.Open(savePath + "/" + textureName + ".png", FileMode.Create);
        var writer = new BinaryWriter(file);
        writer.Write(bytes);
        file.Close();
        writer.Close();
        UnityEngine.Object.DestroyImmediate(png);
        RenderTexture.active = active;
        return true;
    }
}